package com.humanmirror.actions;

import human.Human;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import controller.Controller;

public class LoginCheckAction implements Action {

	@Override
	public String perform(HttpServletRequest request, HttpServletResponse response){

		String login = request.getParameter("login");
		String password = request.getParameter("password");

		Statement stmt = null;
		Connection conn = null;
		ResultSet r =null;

		try{
			Class.forName("org.sqlite.JDBC");
			conn = DriverManager.getConnection("jdbc:sqlite:c:\\EclipseWorkspaceEE\\HumanMirror2\\HM.sqlite");
			//E:\\Eclipse Workspace EE\\HumanMirror\\HM.sqlite
			//C:\\EclipseWorkspaceEE\\HumanMirror\\HM.sqlite			
			stmt = conn.createStatement();

			stmt.execute("SELECT * FROM USERS WHERE LOGIN='" + login +
					"' AND PASSWORD='" + password + "'");
			r = stmt.getResultSet();

			if (r.next()) {
				HttpSession session = request.getSession(true);
				session.setAttribute("user", login);
				session.setAttribute("controller", new Controller(new Human()));
				session.setAttribute("questionNumber", 0);
				return "/main.jsp";
			} else {
				request.setAttribute("errorMessage", "Invalid username/password.");
				return "/error.jsp";
			}

		} catch (Exception e){
			e.printStackTrace();
		} finally {

			try {
				stmt.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}		
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}

		}//finally	
		return null;
	}//perform

}
